package services

import (
	"context"
	"encoding/json"
	"log"
	"saasems/database"
	"saasems/models" // Add this import
)

type RuleLearningService struct {
	db *database.PostgresDB
}

func NewRuleLearningService(db *database.PostgresDB) *RuleLearningService {
	return &RuleLearningService{db: db}
}

func (s *RuleLearningService) LearnAndPredict(ctx context.Context, tenantID string) error {
	// 获取历史数据
	var histories []models.BusinessRuleHistory
	if err := s.db.GetDB().WithContext(ctx).Where("tenant_id = ?", tenantID).Find(&histories).Error; err != nil {
		return err
	}

	// 将数据发送到ollama的mcp server进行学习
	if err := s.sendToOllama(histories); err != nil {
		return err
	}

	// 获取预测结果并更新数据库
	predictions, err := s.getPredictionsFromOllama(tenantID)
	if err != nil {
		return err
	}

	return s.updatePredictions(ctx, predictions)
}

func (s *RuleLearningService) sendToOllama(histories []models.BusinessRuleHistory) error {
	// 实现将历史数据发送到ollama的mcp server的逻辑
	data, err := json.Marshal(histories)
	if err != nil {
		return err
	}

	// 发送数据到ollama
	log.Printf("Sending data to ollama: %s", string(data))
	return nil
}

func (s *RuleLearningService) getPredictionsFromOllama(tenantID string) (map[string]string, error) {
	// 实现从ollama获取预测结果的逻辑
	return map[string]string{
		"rule1": "prediction1",
		"rule2": "prediction2",
	}, nil
}

func (s *RuleLearningService) updatePredictions(ctx context.Context, predictions map[string]string) error {
	// 更新预测结果到数据库
	for ruleID, prediction := range predictions {
		if err := s.db.GetDB().WithContext(ctx).Model(&models.BusinessRuleHistory{}).
			Where("id = ?", ruleID).
			Update("prediction", prediction).Error; err != nil {
			return err
		}
	}
	return nil
}
